#include "SkinLoader.h"
#include "SkinObjManager.h"
#include <Shlwapi.h>
#pragma comment(lib,"msxml2.lib")

CSkinLoader::CSkinLoader()
{
}

CSkinLoader::~CSkinLoader()
{
}

BOOL CSkinLoader::LoadXml( UINT uResID )
{
    return TRUE;
}

BOOL CSkinLoader::LoadXml( LPCTSTR xmlName )
{
    if ( !PathFileExists( xmlName ) )
    {
        return FALSE;
    }

    CComPtr<IXMLDOMDocument> spXMLDoc;
    HRESULT hr = spXMLDoc.CoCreateInstance( CLSID_DOMDocument2 );

    if ( FAILED( hr ) || spXMLDoc == NULL )
        return FALSE;

    spXMLDoc->put_async( VARIANT_FALSE );
    VARIANT_BOOL  bLoad;
    hr = spXMLDoc->load( CComVariant( xmlName ), &bLoad );

    if ( bLoad == VARIANT_FALSE )
        return FALSE;

    IXMLDOMDocument* pXmlDoc = spXMLDoc.Detach();
    return loadNode( pXmlDoc );
}

BOOL CSkinLoader::loadNode( IXMLDOMDocument* pXmlDoc )
{
    CSkinObjManager* pObjMgr = CSkinObjManager::GetHinstance();
    CComPtr<IXMLDOMNodeList> rootChildList;
    pXmlDoc->get_childNodes( &rootChildList );
    LONG childCount = 0;
    rootChildList->get_length( &childCount );

    for ( LONG i = 0; i < childCount; i++ )
    {
        CComPtr<IXMLDOMNode> rootChildNode;
        rootChildList->get_item( i, &rootChildNode );
        CComBSTR childName;
        rootChildNode->get_nodeName( &childName );

        if ( 0 == _tcscmp( childName, _T( "xml" ) ) )
        {
            continue;
        }

        CComPtr<IXMLDOMNodeList> rootNodeList;
        HRESULT hr = rootChildNode->get_childNodes( &rootNodeList );
        long nodeCount = 0;
        rootNodeList->get_length( &nodeCount );

        for ( long i = 0; i < nodeCount; i++ )
        {
            CComBSTR nodeName;
            CComPtr<IXMLDOMNode> xmlNode;
            hr = rootNodeList->get_item( i, &xmlNode );
            hr = xmlNode->get_nodeName( &nodeName );

            if ( S_OK == hr )
            {
                CSkinWindowBase* pWndBase = pObjMgr->CreateObject( nodeName );
                pWndBase->LoadNode( xmlNode );
            }
        }
    }

    return TRUE;
}